package com.iwhalecloud.bss.kite.cucc.web.controller.oss;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.model.OSSObjectSummary;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.cucc.client.api.oss.IAliyunOssService;
import com.iwhalecloud.bss.kite.cucc.client.vo.order.AliyunOssResultVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RequestMapping("/aliyunOss")
@RestController
@Api(tags = {
    "/aliyunOss - 阿里云OSS"
})
public class AliyunOssController {

    @Autowired
    private IAliyunOssService aliyunOssService;

    @ApiOperation(value = "附件预览（适用于所有文件预览）、返回文件路径", notes = "附件预览（适用于所有文件预览）、返回文件路径")
    @GetMapping(value = "/ossView")
    public DataResult<String> ossView(@RequestParam String objectName) {
        return ErrorConsts.SUCCESS.getResult(aliyunOssService.getUrl(objectName, System.currentTimeMillis()));
    }

    @PostMapping(value = "/uploadFile")
    public DataResult<AliyunOssResultVO> uploadFile(@RequestParam(value = "file", required = false) MultipartFile file,
                                                                       String strPath, HttpServletRequest request) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String objectName = strPath+"/"+ UUID.randomUUID().toString()+"."+suffix;
        //String ip = getIpAddr(request);
        AliyunOssResultVO aliyunOssResultVO = aliyunOssService.upload(file.getInputStream(), objectName);
        return ErrorConsts.SUCCESS.getResult(aliyunOssResultVO);
    }

    @PostMapping(value = "/listOSSObjectSummary")
    public DataResult<List<OSSObjectSummary>> listOSSObjectSummary(){
        return ErrorConsts.SUCCESS.getResult(aliyunOssService.listOSSObjectSummary());
    }


    @GetMapping(value = "/download")
    public DataResult<Map<String, Object>> download(@RequestParam("fileName") String objectName, HttpServletResponse response) throws IOException {
        Map<String, Object> result = new HashMap<>();
        try {
            //通知浏览器以附件形式下载
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(objectName.getBytes(), "utf-8"));
            aliyunOssService.exportOssFileStream(response.getOutputStream(), objectName);
            result.put("0", "下载成功");
        }
        catch (Exception e) {
            result.put("1", "下载失败");
            ErrorConsts.SYSTEM_ERROR.throwOut(e.getMessage());
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }

    /**
     * 获取IP地址
     *
     * @param request 请求对象
     * @return IP地址
     */
    public String getIpAddr(HttpServletRequest request) {
        String header1 = "x-forwarded-for";
        String header2 = "Proxy-Client-IP";
        String header3 = "WL-Proxy-Client-IP";
        String ip1 = "unknown";
        String ip2 = "127.0.0.1";
        String ip3 = "0:0:0:0:0:0:0:1";
        String ipAddress = request.getHeader(header1);
        if (ipAddress == null || ipAddress.length() == 0 || ip1.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(header2);
        }
        if (ipAddress == null || ipAddress.length() == 0 || ip1.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader(header3);
        }
        if (ipAddress == null || ipAddress.length() == 0 || ip1.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ip2.equals(ipAddress) || ip3.equals(ipAddress)) {
                //根据网卡取本机配置的IP
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ipAddress = inet.getHostAddress();
                }
                catch (UnknownHostException e) {
//                    e.printStackTrace();
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        int i = 15;
        if (ipAddress != null && ipAddress.length() > i) {
            String split = ",";
            if (ipAddress.indexOf(split) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(split));
            }
        }
        return ipAddress;
    }
}
